use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
struct sdl2tool {
    context: sdl2::Sdl,
    eventpump: sdl2::EventPump,
    //window: sdl2::video::Window,
    canvas: sdl2::render::WindowCanvas,
    update: fn(),
}
impl sdl2tool {
    fn init() -> sdl2tool {
        let sdl_context = sdl2::init().expect("");
        let video_subsystem = sdl_context.video().expect("");
        let mut _window = video_subsystem
            .window("rust-sdl2 demo", 800, 600)
            .position_centered()
            .build()
            .expect("");
        //into_canvas 是 self 不是 &self，會搶走 _window,這之後無法再訪問 _window
        let mut _canvas = _window.into_canvas().build().unwrap();
        let event_pump = sdl_context.event_pump().unwrap();

        let mut win = sdl2tool {
            context: sdl_context,
            eventpump: event_pump,
            //window: _window,
            canvas: _canvas,
            update:||{},
        };
        win.canvas.set_draw_color(Color::RGB(0, 255, 255));
        win.canvas.clear();
        win.canvas.present();
        return win;
    }
    // fn init(&self) -> std::result::Result<(), String> {
    //     return Err(String::from("err"));
    // }
    fn winloop(&mut self) {
        let mut i = 0;

        'running: loop {
            let up = self.update;
            up();
            i = (i + 1) % 255;
            self.canvas.set_draw_color(Color::RGB(i, 64, 255 - i));
            self.canvas.clear();
            for event in self.eventpump.poll_iter() {
                match event {
                    Event::Quit { timestamp: u32 } => break 'running,
                    Event::KeyDown {
                        keycode: Some(Keycode::Escape),
                        ..
                    } => break 'running,
                    _ => {}
                }
            }
            self.canvas.present();
            let sleeptime = std::time::Duration::from_millis(20);
            std::thread::sleep(sleeptime);
        }
    }
}

fn main() {
    let mut win = sdl2tool::init();
    win.update =frame;
    win.winloop();
}
fn frame() {
    println!("tline");
}
